package com.zac.digest;

import java.security.*;

/**
 * @author ZacTse
 *
 */
public class myDigest {
	
	public static void main(String[] args) {
		myDigest my = new myDigest();
		my.testDigest();
	}

	public void testDigest() {
		try {
			String myinfo = "My test info.";
			java.security.MessageDigest alga = java.security.MessageDigest
					.getInstance("MD5");
			/*
			 * java.security.MessageDigest alga = java.security.MessageDigest
			 * .getInstance("SHA-1");
			 */
			alga.update(myinfo.getBytes());
			byte[] digesta = alga.digest();
			//System.out.println(digesta.toString());
			System.out.println("Digest : " + byte2hex(digesta));
			// Transport your info and digest to your friend through certain
			// way, he will be able to tell the correctness.
			java.security.MessageDigest algb = java.security.MessageDigest
					.getInstance("MD5");
			algb.update(myinfo.getBytes());
			if (MessageDigest.isEqual(digesta, algb.digest())) {
				System.out.println("Match!");
			} else {
				System.out.println("Unmatched!");
			}
		} catch (java.security.NoSuchAlgorithmException ex) {
			System.out.println("Illegal algorithm!");
		}
	}

	/**
	 * @param b The byte array to be converted to hexadecimal string
	 * @return The hexadecimal string
	 */
	public String byte2hex(byte[] b) //
	{
		String hs = "";
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1)
				hs = hs + "0" + stmp;
			else
				hs = hs + stmp;
			if (n < b.length - 1)
				hs = hs + ":";
		}
		return hs.toUpperCase();
	}
}